const express = require('express');
const router = express.Router();
const Mock = require("mockjs");//随机生成一些假数据
// const s = new Intl.DateTimeFormat('zh-cn');//优化时间格式
const crypto = require("crypto");//crypto模块功能是加密并生成各种散列
const jwt = require("jsonwebtoken");
const formidable = require('formidable');//上传头像
// const { stringify } = require("qs");//
const fs = require('fs');
const { Uid, Userinfo, Article } = require('../utils/schema.js');

const Random = Mock.Random;
var userObj = ''
// const { keys, aesEncrypt, aesDecrypt } = require("../utils/index");

/***********************/
router.get("/demo", (req, res) => {
  res.json({
    code: 200,
    msg: "demo is success",
    query: req.query
  })
})

// mock假数据接口api
router.get("/mock/data", (req, res) => {
  let articles = [];
  for (let i = 0; i < 100; i++) {
    let newArticleObject = {
      uid: Random.id(),
      title: Random.csentence(5, 30),//句子段落
      city: Random.city(),
      thumbnail_pic_s: Random.image('200x200', '#02adea', 'wuhan1910'),
      author_name: Random.cname(),//中文名字
      date: Random.date('yyyy-MM-dd') + " " + Random.time()
    }
    articles.push(newArticleObject);
  };
  res.json({
    result: articles,
    code: 200,
    msg: "获取mock假数据成功!"
  })
})

/********* 验证token-中间件 **************/
router.use(function (req, res, next) {
  // c onsole.log('url',req.url)    url /register
  // c onsole.log('path',req.path)  path /register
  // c onsole.log(req.originalUrl)  /blog/register
  if (req.path !== "/login" && req.path !== "/register" && req.path !== "/all-article" && req.path !== '/user') {
    //验证
    // 如果token解析失败或者token已经过期，则都会返回err，只有正确解析出用户数据才会返回data
    jwt.verify(req.headers.token, "topaz-blog", (err, data) => {
      // console.log(data)
      userObj = data
      if (!err) {
        next();
      }
      else {
        res.json({
          code: false,
          // status: -1,
          msg: 'token验证失败',
          result: null
        })
      }
    })
  }
  else {  //登录和注册可以正常访问接口
    next();
  }
})

/***********************/
router.post("/login", (req, res) => {
  const { email, password } = req.body;
  //对password进行加密
  const hash = crypto.createHmac('sha256', password)
    .update('topaz-blog')
    .digest('hex');
  Userinfo.find({
    // 存在与否,密码是否正确一起判断了
    email, password: hash
  }).then(result => {
    if (result.length > 0) {
      // 后端加密生成发送给前端,前端保存在sessionStorage里面
      // const token = aesEncrypt(email, keys);
      // req.session.token = token;//保存在后端的令牌-session存在跨域问题
      // 就算是允许所有域都不行,也要配置代理
      // 制作令牌
      // 将参数按照解密规则加密生成签名sign
      const token = jwt.sign({ email, time: Date.now() }, "topaz-blog", { expiresIn: 60 * 60 * 6 });

      // 退出时需要清理掉
      req.session.email = email;
      res.cookie("token", token);

      Userinfo.updateOne({ email, password: hash }, {
        $set: {
          token
        }
      }).then(() => {
        res.json({
          code: 200,
          msg: "登录成功",
          result: token,
          email
        })
      })
    } else {
      // 没有这个用户
      res.json({
        code: 200,
        msg: "用户名或者密码错误",
        result: null
      });
    }
  });
})


router.post("/register", (req, res) => {
  // 判断都在后端执行,前端只要保证传的数据合乎规范(比如判断用户名是否存在)
  const { email, nickname, password, agreement } = req.body;
  // headers是表单类型-不能直接拿到,要转数据结构
  Userinfo.find({
    email
  }).then(result => {
    if (result.length > 0) {
      res.json({
        code: 200,
        msg: "已注册,请直接登录",
        result: null
      });
    } else {
      //先存(刚开始是id:0;直接取是从0开始的,等更新后再取)
      Uid.updateOne({
        username: "bloger"
      }, {
        $inc: {
          id: 1
        }
      }).then(() => {
        Uid.findOne({//再取
          username: "bloger"
        }).then(last => {
          //对password进行加密
          const hash = crypto.createHmac('sha256', password)
            .update('topaz-blog')
            .digest('hex');
          const registration_time = new Date()
          const uid = last.id;
          // new User({ email, password: hash }).save().then(() => { //注册
          //   res.json({
          //     status: 0
          //   })
          // })
          Userinfo.insertMany({ registration_time, uid, email, nickname, password: hash, agreement, collectList: [], avatar: '', token: '' }).then(() => {
            res.json({
              code: 200,
              msg: "注册成功",
              result: true
            });
          })
        })
      })
    }
  })
});

router.post("/pub", (req, res) => {
  const data = req.body
  if (data.id) {//更新
    Article.update({ _id: data.id }, {
      $set: {
        html: data.html,
        text: data.text,
        isPub: data.isPub,
        isDraft: data.isDraft,
        tags: data.tags,
        title: data.title,
        time: new Date()
      }
    }).then(result => {
      if (result.nModified) {
        res.json({
          code: 200,
          masg: '文章已更新上传',
          // result: data,
          email: userObj.email
        })
      }
    })
  } else {//上传
    Userinfo.findOne({ token: req.headers.token }).then(user => {
      Article.insertMany([{ author: userObj.email, ...data, time: new Date().getTime(), praisePoints: [], commentNum: [], avatar: user.avatar }]).then(result => {
        if (result.length > 0) {
          res.json({
            code: 200,
            masg: '文章已更新上传',
            // result: data,
            email: userObj.email
          })
        }
      })
    })
  }
});

router.post("/all-article", (req, res) => {
  Article.find().then(result => {
    if (result.length > 0) {
      res.json({
        code: 200,
        masg: '获取全部文章',
        result
      })
    } else {
      res.json({
        code: 200,
        masg: '暂无文章',
        result
      })
    }
  })
});

router.post("/delete-blog", (req, res) => {
  // console.log(req.body.id)
  Article.deleteOne({ _id: req.body.id }).then(result => {
    if (result.deletedCount) {
      res.json({
        code: 200,
        masg: '删除成功',
        result
      })
    }
  })
});

router.post("/details-blog", (req, res) => {
  // console.log(req.body.id)
  Article.findOne({ _id: req.body.id }).then(result => {
    // console.log(result)
    res.json({
      code: 200,
      masg: 'blog详情',
      result
    })
  })
});

router.post("/comment-blog", (req, res) => {
  console.log(req.body.id)
  console.log(req.body.commentList)
  Article.updateOne({ _id: req.body.id }, {
    $set: {
      commentNum: req.body.commentList
    }
  }).then(list => {
    if (list.nModified) {
      Article.find().then(result => {
        if (result.length > 0) {
          res.json({
            code: 200,
            masg: '获取全部文章',
            result
          })
        } else {
          res.json({
            code: 200,
            masg: '暂无文章',
            result
          })
        }
      })
    }
  })
});

router.post("/support-blog", (req, res) => {
  const data = req.body
  Article.updateOne({ _id: data.id }, {
    $set: {
      praisePoints: data.praisePoints
    }
  }).then(support => {
    if (support.nModified) {
      Article.find().then(result => {
        if (result.length > 0) {
          res.json({
            code: 200,
            masg: '获取全部文章',
            result
          })
        } else {
          res.json({
            code: 200,
            masg: '暂无文章',
            result
          })
        }
      })
    }
  })
});

router.post("/collect-user", (req, res) => {
  const data = req.body
  Userinfo.updateOne({ token: req.headers.token }, {
    $set: {
      collectList: data.collectList
    }
  }).then(list => {
    if (list.nModified) {
      Userinfo.findOne({ token: req.headers.token }).then(result => {
        res.json({
          code: 200,
          msg: '修改收藏',
          result
        })
      })
    }
  })
});

router.post("/quit", (req, res) => {
  Userinfo.updateOne({ token: req.headers.token }, {
    $set: {
      token: ''
    }
  }).then(() => {
    req.session.email = null;
    if (req.cookies.token) {
      res.cookie("token", "")
    }
    res.json({
      code: 200,
      msg: '退出成功',
      result: null
    })
  })
})

router.post("/user", (req, res) => {
  Userinfo.findOne({ token: req.headers.token }).then(result => {
    res.json({
      code: 200,
      msg: '获取个人信息',
      result
    })
  })
})

router.post("/modify-pwd", (req, res) => {
  const { oldPassword, password, confirm } = req.body
  const hash = crypto.createHmac('sha256', oldPassword)
    .update('topaz-blog')
    .digest('hex');
  const newHash = crypto.createHmac('sha256', password)
    .update('topaz-blog')
    .digest('hex');
  Userinfo.updateOne({ token: req.headers.token, password: hash }, {
    $set: {
      password: newHash
    }
  }).then(result => {
    if (result.nModified === 1) {
      res.json({
        code: 200,
        msg: '修改成功',
        result
      })
    } else {
      res.json({
        code: 200,
        msg: '修改失败',
        result: null
      })
    }
  })
})

router.post("/upload", (req, res) => {
  const form = formidable({ multiples: false });
  form.uploadDir = "./public/blog-avatar/"  //设置上传路径
  form.parse(req, (err, fields, files) => {

    if (!files.file) return;  //没有上传文件，不进行任何处理
    //上传文件重命名
    fs.renameSync(files.file.path, form.uploadDir + files.file.name);
    // 文章
    // console.log(userObj.email)
    Article.updateMany({ author: userObj.email }, {
      $set: {
        avatar: "/blog-avatar/" + files.file.name
      }
    }).then(art => {
      // 用户
      Userinfo.update({ token: req.headers.token }, {
        $set: {
          avatar: "/blog-avatar/" + files.file.name
        }
      }).then(() => {
        res.json({
          code: 200,
          path: "/blog-avatar/" + files.file.name
        })
      })
    })
  });
})


// 导出路由
module.exports = router;
